# -*- coding: utf-8 -*-
import ast
import hashlib
from collections import OrderedDict
import requests
import json

from django.conf import settings

from async import async_job
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import SignError, NotPayOrderError, ProcessedPayOrderError, NotResponsePayIdError
from common.utils.ip_address import check_valid_ip_address

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '37078A99': {
        'API_KEY': '2a4c5e8f5e284130b0473e67cebf79b8',
        'gateway': 'http://139.180.219.238/api/pay/order',  # 请求地址
    }
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _md5(parameter):
    m = hashlib.md5()
    m.update(parameter)
    return m.hexdigest()


# sign=MD5(mchNo+customerNo+orderNo+amount+currency+returnUrl+notifyUrl+MD5key)
def generate_verify_sign(parameter, key):
    s = '%s%s%s%s%s%s%s%s' % (parameter['mchNo'], parameter['customerNo'], parameter['orderNo'],
                              parameter['amount'], parameter['currency'], parameter['returnUrl'],
                              parameter['notifyUrl'], key)
    _LOGGER.info('globalpay request status s:%s' % s)
    return _md5(s)


# sign=MD5(mchNo+customerNo+orderNo+amount+currency+orderId+transactionId+MD5key)
def verify_notify_sign(parameter, key):
    sign = parameter.pop('sign')
    s = '%s%s%s%s%s%s%s%s' % (parameter['mchNo'], parameter['customerNo'], parameter['orderNo'],
                              parameter['amount'], parameter['currency'], parameter['orderId'],
                              parameter['transactionId'], key)
    if sign != _md5(s):
        _LOGGER.info("globalpay sign: %s, calculated sign: %s", sign, _md5(s))
        raise SignError('globalpay sign not pass, data: %s' % parameter)


# 创建支付订单
def create_charge(pay, pay_amount, info):
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    # 请求报文
    parameter_dict = OrderedDict((
        ('mchNo', str(app_id)),
        ('customerNo', str(pay.id)),
        ('orderNo', str(pay.id)),
        ('amount', '%.f' % (float(pay_amount) * 100)),  # 金额为分
        ('currency', 'CNY'),
        ('returnUrl', '{}/pay/api/{}/globalpay/'.format(
            settings.NOTIFY_PREFIX, settings.RETURN_PATH)),
        ('notifyUrl', '{}/pay/api/{}/globalpay/{}'.format(
            settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('signType', 'MD5'),
    ))
    parameter_dict['sign'] = generate_verify_sign(parameter_dict, api_key)
    _LOGGER.info("globalpay create date: %s, order_id is: %s", json.dumps(parameter_dict),
                 parameter_dict['customerNo'])

    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_gateway(app_id), data=parameter_dict, headers=headers, timeout=5)
    data = json.loads(response.text)
    if str(data['code']) == '200':
        url = 'http://139.180.219.238/pay/confirm/%s' % (data['data']['orderId'])
        _LOGGER.info('globalpay response url: %s', url)
        return {'charge_info': url}
    _LOGGER.info('globalpay response msg: %s', data['error'])
    return {'charge_info': data['error']}


# OK
def check_notify_sign(request, app_id):
    _LOGGER.info("globalpay notify body: %s", request.body)
    api_key = _get_api_key(app_id)
    data = ast.literal_eval(request.body)
    _LOGGER.info("globalpay notify data: %s, order_id is: %s", data, data['customerNo'])
    verify_notify_sign(data, api_key)
    pay_id = data['customerNo']
    check_valid_ip_address(str(request.META['REMOTE_ADDR']), pay_id)
    if not pay_id:
        _LOGGER.error("globalpay fatal error, out_trade_no not exists, data: %s", data)
        raise NotResponsePayIdError('globalpay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise NotPayOrderError('globalpay pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ProcessedPayOrderError('globalpay pay %s has been processed' % pay_id)

    mch_id = pay.mch_id  # 商户编号
    trade_status = ''
    trade_no = data['customerNo']
    total_fee = float(data['amount']) / 100  # 单位分转为元
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee,
    }

    check_channel_order(pay_id, total_fee, app_id)
    # 只有支付成功才异步回调
    _LOGGER.info('globalpay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
    order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
    # async notify
    async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    """ 查询订单 """
    pass
